package JavaEE初阶.Multi;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1000);

    public void submit(Runnable runnable) throws InterruptedException{
        queue.put(runnable);
    }

    public MyThreadPool(int n){
        for(int i = 0; i < n; i++){
            Thread t = new Thread(() ->{
                //让这个线程从队列中消费任务，并进行执行
                try{
                    Runnable runnable = queue.take();
                    runnable.run();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }
}

public class Demo{
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0;i < 1000; i++){
            int id = i;
            myThreadPool.submit(new Runnable(){
                @Override
                public void run(){
                    System.out.println("执行任务" + id);
                }
            });

        }
    }
}
